<script>
	import BaseLayout from '@/components/BaseLayout/index.vue';
	import CountDown from '@/components/CountDown/index.vue';
	import {
		conditioningRecordsDetail,
		conditioningSchemeDetail,
		continueConditioningDetail,
		endConditioning,
		endConditioningDetail,
		startConditioningDetail,
		suspendConditioningDetail,
	} from '@/services/api/regulate';
	import AcupunctureDialog from './AcupunctureDialog.vue';
	import HumanBody from './three.vue';

	import {
		VITE_IMAGE_URL,
		VITE_APP_URL
	} from '../../utils/http/url.js'
	export default {
		data() {
			return {
				baseImgUrl: VITE_IMAGE_URL,
				// 调理记录id
				conditioningRecordId: '',
				// 调理方案id
				schemeConditioningId: '',
				// 调理方案详情
				detailInfo: {},
				// 穴位列表
				acupointList: [],
				acupoint: null,
				// 调理记录详情id
				conditioningRecordsDetailsId: '',
				// 倒计时
				groupActive: 0,
				// 停止弹窗
				showStopWin: false,
				// 结束弹窗
				showEndWin: false,
				activeImage: 0,
				bgAudioManager: null,
				bgAudioManager1: null,
				// 穴位描述弹窗
				isShowDialog: false,
				// 是否直接结束整个流程
				isEnd: false,
			}
		},
		components: {
			HumanBody,
			BaseLayout,
			CountDown,
			AcupunctureDialog
		},
		onLoad(option) {
			this.conditioningRecordId = option?.conditioningRecordId;
			this.schemeConditioningId = option?.schemeConditioningId;
			// 获取调理方案详情
			this.getConditioningSchemeDetail();
			// 获取调理记录详情
			this.getConditioningRecordsDetail();
		},
		onShow() {},
		onHide() {},
		onUnload() {
			this.bgAudioManager && this.bgAudioManager.stop();
			this.bgAudioManager && (this.bgAudioManager.src = '');
			this.bgAudioManager1 && this.bgAudioManager1.stop();
			this.bgAudioManager1 && (this.bgAudioManager1.src = '');
		},
		methods: {
			// 获取调理方案详情
			getConditioningSchemeDetail() {
				conditioningSchemeDetail(this.schemeConditioningId)
					.then((res) => {
						this.detailInfo = res.data;
					})
					.catch((err) => {
						console.log('调理方案详情失败', err);
					});
			},
			// 获取调理记录详情
			getConditioningRecordsDetail() {
				conditioningRecordsDetail(this.conditioningRecordId)
					.then((res) => {
						this.acupointList = res.data?.consumerConditioningRecordsDetailsList.map((item) => ({
							...item,
							isStart: false,
							isStop: false
						}));
						// 处理当前调理步骤 - 边界情况-调理中设备断电
						this.handleConditioningOrder();
					})
					.catch((err) => {
						console.log('获取调理记录详情失败', err);
					});
			},
			handleConditioningOrder() {
				// 判断 acupointList 中的每一项的 status 找出来第一个不为 2 的 index 作为当前调理步骤
				const index = this.acupointList.findIndex((item) => item.status !== '2');
				this.groupActive = index;
				this.conditioningRecordsDetailsId = this.acupointList[index].id;
				this.acupoint = this.acupointList[index].schemeAcupointList;

				// 并且如果等于 1 说明已经开始调理了 直接调用开始调理的方法
				if (this.acupointList[index].status === '1') {
					this.handleStart();
				}
			},
			handleTimeEnd() {
				this.handleEndGroup();
			},
			// 开始调理
			handleStart() {
				startConditioningDetail({
						conditioningRecordsDetailsId: this.conditioningRecordsDetailsId
					})
					.then(() => {
						this.andriodFun(0)
						this.acupointList[this.groupActive].isStart = true;
						this.acupointList[this.groupActive].isStop = false;
						// 播放提示音乐
						// this.playAudio1('../../static/mp3/start.mp3');
						this.playAudio1(
							"http://shebei.yeeyoofun.com/Gas-Wave-Admin-Api/profile/upload/2025/06/06/start_20250606135648A007.mp3"
						)

						// 1s后播放调理音乐
						const audioTimer = setTimeout(() => {
							// 播放调理音乐
							this.handleAudio();
							clearTimeout(audioTimer);
						}, 1500);

						this.$nextTick(() => {
							setTimeout(() => {
								this.$refs.countDown.start();
							}, 1000);
						});
					})
					.catch((err) => {
						console.log('开始调理失败', err);
					});
			},
			// 暂停调理
			handleStop() {
				suspendConditioningDetail({
						conditioningRecordsDetailsId: this.conditioningRecordsDetailsId
					})
					.then(() => {
						this.andriodFun(1)
						this.acupointList[this.groupActive].isStop = true;
						// 暂停音乐
						window.JYJSInterface.pauseMusic();
						// this.bgAudioManager && this.bgAudioManager.pause();
						// 播放提示音乐
						// this.playAudio1('../../static/mp3/pause.mp3');
						// this.playAudio1(
						// 	"http://shebei.yeeyoofun.com/Gas-Wave-Admin-Api/profile/upload/2025/06/06/pause_20250606135623A006.mp3"
						// );
						this.$nextTick(() => {
							this.$refs.countDown.pause();
						});
					})
					.catch((err) => {
						console.log('暂停调理失败', err);
					});
			},
			// 继续调理
			handleContinue() {
				continueConditioningDetail({
						conditioningRecordsDetailsId: this.conditioningRecordsDetailsId
					})
					.then(() => {
						this.andriodFun(0)
						this.acupointList[this.groupActive].isStop = false;
						// 播放提示音乐
						// this.playAudio1('../../static/mp3/continue.mp3');
						// this.playAudio1(
						// 	'http://shebei.yeeyoofun.com/Gas-Wave-Admin-Api/profile/upload/2025/06/06/continue_20250606135438A003.mp3'
						// );

						const audioTimer = setTimeout(() => {
							// 继续音乐
							window.JYJSInterface.resumeMusic()
							// this.bgAudioManager && this.bgAudioManager.play();
							clearTimeout(audioTimer);
						}, 1000);

						this.$nextTick(() => {
							this.$refs.countDown.start();
						});
					})
					.catch((err) => {
						console.log('继续调理失败', err);
					});
			},
			// 停止调理-每一组的调理结束 时间结束自动触发
			handleEndGroup() {
				endConditioningDetail({
						conditioningRecordsDetailsId: this.conditioningRecordsDetailsId
					})
					.then(() => {
						this.acupointList[this.groupActive].isStart = false;
						this.acupointList[this.groupActive].isStop = false;
						if (this.groupActive === this.acupointList.length - 1) {
							this.handleEnd();
						} else {
							this.andriodFun(1)
							this.groupActive++;
							this.conditioningRecordsDetailsId = this.acupointList[this.groupActive].id;
							this.acupoint = '';
							this.activeImage = 0;
							// 暂停音乐
							// this.bgAudioManager && this.bgAudioManager?.stop();
							// 播放提示音乐
							// this.playAudio1('../../static/mp3/end.mp3');
							this.playAudio1(
								'http://shebei.yeeyoofun.com/Gas-Wave-Admin-Api/profile/upload/2025/06/06/end_20250606135527A004.mp3'
							);
							setTimeout(() => {
								this.acupoint = this.acupointList[this.groupActive].schemeAcupointList;
							}, 300);
						}
					})
					.catch((err) => {
						console.log('停止调理失败', err);
					});
			},
			// 停止调理-整个流程结束 手动点击停止调理
			// 先结束当前这一组的调理，然后再结束整个流程
			// 结束这一组的流程
			handleEnd1() {
				if (this.isEnd) {
					// 结束整个流程
					this.handleEnd();
					return;
				}

				endConditioningDetail({
						conditioningRecordsDetailsId: this.conditioningRecordsDetailsId
					})
					.then(() => {
						this.handleEnd();
					})
					.catch((err) => {
						console.log('停止调理失败', err);
					});
			},
			// 结束整个流程
			handleEnd() {
				endConditioning({
						conditioningRecordId: this.conditioningRecordId
					})
					.then(() => {
						this.andriodFun(1)
						this.acupointList[this.groupActive].isStart = false;
						this.acupointList[this.groupActive].isStop = false;
						this.showStopWin = false;
						// this.bgAudioManager && this.bgAudioManager?.stop();
						// this.bgAudioManager && (this.bgAudioManager.src = '');
						// 播放提示音乐
						// this.playAudio1('../../static/mp3/more.mp3');
						this.playAudio1(
							"http://shebei.yeeyoofun.com/Gas-Wave-Admin-Api/profile/upload/2025/06/06/more_20250606135556A005.mp3"
						);

						this.showEndWin = true;
					})
					.catch((err) => {
						console.log('停止调理失败', err);
					});
			},
			// 流程结束跳转首页
			handleToIndex() {
				this.showEndWin = false;
				uni.reLaunch({
					url: '/pages/index/index'
				});
			},
			andriodFun(type) {
				if (type == 0) {
					window.JYJSInterface.startAll();
				} else {
					window.JYJSInterface.stopAll();
				}
			},
			handleScroll() {
				this.$nextTick(() => {
					// 获取元素距离顶部的距离 用于判断是否在可视区域内 (固定高度的情况下)
					let top = 188;
					const query1 = uni.createSelectorQuery().in(this);
					query1
						.selectAll('.group-wrap')
						.boundingClientRect((rects) => {
							top = rects[0].top;
						})
						.exec();

					const query = uni.createSelectorQuery().in(this);
					query
						.selectAll('.content123')
						.boundingClientRect((rects) => {
							let status = true;
							rects.forEach((rect, index) => {
								if (rect.top < top) {
									status = false;
									this.activeImage = index + 1;
								}
							});
							if (status) {
								this.activeImage = 0;
							}
						})
						.exec();
				});
			},
			// 处理音乐路径
			// 读取手机存储中目标文件夹下的所有音频文件,根据名字查找有没有与 musicKey 相同的音频文件,有则播放,没有则使用 fiveElementsListMap 中 musicKey 对应的音频 url 并且下载到本地
			handleAudio() {
				// 获取缓存中的 fiveElementsListMap  musicKey
				const musicKey = uni.getStorageSync('musicKey');
				const fiveElementsListMap = uni.getStorageSync('fiveElementsListMap');

				// 没有则不播放 或者 fiveElementsListMap 中没有 musicKey 对应的音频 url 也不播放
				if (!musicKey || !fiveElementsListMap[musicKey].music) return;

				const baseUrl = VITE_APP_URL;
				const url = `${baseUrl}${fiveElementsListMap[musicKey].music}`;
				this.playAudio(url);
			},
			// 播放音乐 调理音乐
			playAudio(url) {
				window.JYJSInterface.playMusic(url);

				// this.bgAudioManager = uni.createInnerAudioContext();
				// this.bgAudioManager.src = url;
				// this.bgAudioManager.volume = 1;
				// this.bgAudioManager.obeyMuteSwitch = false;
				// this.bgAudioManager.loop = true;
				// this.bgAudioManager.sessionCategory = 'ambient';
				// this.bgAudioManager.play();
				// this.bgAudioManager.onEnded(() => {
				// 	this.bgAudioManager.src = url;
				// 	this.bgAudioManager.play();
				// });
			},
			// 播放音乐 状态提示音乐
			playAudio1(url) {
				window.JYJSInterface.playMusic(url);

				// this.bgAudioManager1 = uni.createInnerAudioContext();
				// this.bgAudioManager1.src = url;
				// this.bgAudioManager1.volume = 1;
				// this.bgAudioManager1.obeyMuteSwitch = false;
				// this.bgAudioManager1.sessionCategory = 'ambient';
				// this.bgAudioManager1.play();
			},
			// 开始调理 旁边的停止调理
			handleEnd2() {
				this.showStopWin = true;
				this.isEnd = true;
			},
			back() {
				uni.navigateBack()
			}
		},
	}
</script>

<template>
	<view class="uno-w-full uno-h-100vh uno-relative">
		<BaseLayout>
			<view class="uno-m-auto bg1 uno-relative" style="width: 685rpx;height: 84%;padding: 20rpx;margin-top: 2%;">
				<!-- 方案切换 -->
				<view class="uno-absolute "
					style="min-width: 26rpx;height: 21rpx;background: rgba(155,187,255,0.2);border-radius: 20rpx;top: 40rpx;right:34rpx">
					<view class="uno-w-full uno-h-full uno-flex uno-items-center uno-justify-between"
						style="padding: 0 6rpx;">
						<view v-for="(_item, index) in acupointList" :key="index"
							:class="[groupActive === index ? 'active' : '', 'tab-item']">
							{{ index + 1 }}
						</view>
					</view>
				</view>
				<!-- 方案 -->
				<view v-if="acupointList.length" class="uno-w-full uno-h-full uno-flex">
					<view class="uno-h-full" style="width: 52%;padding: 20rpx;">
						<view class="uno-c-#fff uno-flex uno-items-center"
							style="font-size: 13rpx;font-weight: 700;color: #FFFFFF;">
							<text>{{ detailInfo.conditioningName }}-组{{ groupActive + 1 }}</text>
							<text class=""
								style="color: #FFD040;font-weight: 600;font-size: 10rpx;margin-left: 10rpx;">本组时长：{{ acupointList[groupActive].conditioningDuration }}秒</text>
							<view class="bg3 flex-center uno-c-#fff"
								style="margin-left: 18rpx;width: 50rpx;height: 20rpx;font-size: 5rpx;font-weight: 500;color: #FFFFFF;"
								@click="isShowDialog = true">
								查看穴位
							</view>
						</view>
						<view class="uno-w-full uno-relative" style="height: 90%;margin-top: 10rpx;">
							<view class="uno-w-full uno-h-full uno-overflow-hidden" style="border-radius: 6rpx;">
								<image
									:src="`${baseImgUrl}${acupointList[groupActive].schemeAcupointList[activeImage].acupointImage || ''}`"
									mode="scaleToFill" style="width: 100%; height: 100%" />
							</view>
							<view v-if="acupoint" class="uno-absolute bg2"
								style="width: 80%;height: 50%;left: -23%;bottom: 0;">
								<!-- <HumanBody v-if="acupoint" :acupoint="acupoint" /> -->
							</view>
						</view>
					</view>
					<view class="uno-h-full" style="width: 48%;padding: 15rpx 20rpx;">
						<view class="uno-w-full"
							style="text-align: right;font-size: 10rpx;font-weight: 700;color: #6CD4FF;margin-top: 40rpx;">
							总时长: {{ detailInfo.conditioningDuration }}秒
						</view>

						<view class="group-wrap">
							<scroll-view scroll-y class="uno-w-full uno-h-full" @scroll="handleScroll">
								<view v-for="(item, index) in acupointList[groupActive].schemeAcupointList"
									:key="item.id" class="content123" style="margin-bottom: 30rpx;min-height: 60%;">
									<view class="uno-c-#fff" style="font-size: 15rpx;color: #FFFFFF;">
										{{ item.acupointName }}
									</view>
									<view class="uno-c-#fff" style="font-size: 9rpx;margin-top: 12rpx;color: #FFFFFF;">
										<rich-text :nodes="item.introduction"></rich-text>
										<!-- <tm-html :content="item.introduction" /> -->
									</view>
								</view>
							</scroll-view>
						</view>

						<!-- 开始调理 -->
						<view v-if="!acupointList[groupActive].isStart" class="flex-center" style="margin-top: 20rpx;">
							<image src="../../static/images/kstl_icon_an.png" mode="scaleToFill" class=""
								style="width: 97rpx;height: 37rpx;" @click="handleStart" />
							<!-- 停止 -->
							<image src="../../static/images/tztl_icon_tztl.png" mode="scaleToFill" class=""
								style="width: 97rpx;height: 37rpx;margin-left: 20rpx;" @click="handleEnd2" />
						</view>

						<!-- 停止调理 -->
						<view v-if="acupointList[groupActive].isStart"
							class="uno-flex uno-items-center uno-justify-center uno-flex-col"
							style="margin-top: 10rpx;">
							<view class="uno-flex uno-items-center">
								<image src="../../static/images/tztl_icon_sc.png" mode="scaleToFill" class=""
									style="width: 13rpx;height: 13rpx;" />
								<text :key="groupActive" class=""
									style="font-size: 13rpx;color: white;font-weight: 700;margin-left: 6rpx;">
									<CountDown ref="countDown" :key="groupActive" :autoStart="false" color="#fff"
										format="MM:SS" :fontSize="13"
										:time="acupointList[groupActive].conditioningDuration * 1000"
										@end="handleTimeEnd" />
								</text>
							</view>
							<view class="flex-center uno-w-full">
								<!-- 暂停 -->
								<image v-if="!acupointList[groupActive].isStop"
									src="../../static/images/tztl_icon_zttl.png" mode="scaleToFill" class=""
									style="width: 97rpx;height: 37rpx;" @click="handleStop" />
								<!-- 继续 -->
								<image v-if="acupointList[groupActive].isStop"
									src="../../static/images/kstl_icon_jxtl.png" mode="scaleToFill" class=""
									style="width: 97rpx;height: 37rpx;" @click="handleContinue" />
								<!-- 停止 -->
								<image src="../../static/images/tztl_icon_tztl.png" mode="scaleToFill" class=""
									style="width: 97rpx;height: 37rpx;margin-left: 20rpx;"
									@click="showStopWin = true" />
							</view>
						</view>
						<view class="" style="display: flex;justify-content: space-between;margin-top: 20rpx;">
							<view class="">

							</view>
							<image src="../../static/images/qrfa_icon_fh.png" mode="scaleToFill" class=""
								style="width: 44rpx;height: 21rpx;margin-right: 16rpx;" @click="back" />
						</view>

						<!-- 弹窗 调理停止提示 -->
						<view v-if="showStopWin" class="bg-dialog" style="width: 194rpx;height: 134rpx;">
							<view class="uno-relative uno-w-full uno-h-full">
								<view class=""
									style="width: 60%;height: 10rpx;margin-top: 8rpx;margin-left: 14rpx;color: #00D4FF;font-size: 7rpx;">
									调理停止提示</view>
								<view class="uno-m-auto flex-center" style="width: 80%;height: 46%;margin-top: 14rpx;">
									<view class="" style="color: #00D4FF;font-size: 9rpx;font-weight: 700;">
										您确定要停止本次调理流程吗？</view>
								</view>
								<view class="uno-w-full flex-center">
									<image src="../../static/images/queding.png" mode="scaleToFill" class=""
										style="width: 44rpx;height: 18rpx;margin-right: 10rpx;" @click="handleEnd1" />
									<image src="../../static/images/quxiao.png" mode="scaleToFill" class=""
										style="width: 44rpx;height: 18rpx;" @click="showStopWin = false" />
								</view>
							</view>
						</view>

						<!-- 弹窗 调理结束提示 -->
						<view v-if="showEndWin" class="bg-dialog" style="width: 194rpx;height: 134rpx;">
							<view class="uno-relative uno-w-full uno-h-full">
								<view class=""
									style="width: 60%;height: 10rpx;margin-top: 8rpx;margin-left: 14rpx;color: #00D4FF;font-size: 7rpx;">
									调理结束提示</view>
								<view class="uno-m-auto flex-center uno-flex-col"
									style="width: 80%;height: 46%;margin-top: 14rpx;">
									<view class="" style="color: #00D4FF;font-size: 9rpx;font-weight: 700;">本次调理结束，谢谢！
									</view>
									<view class="" style="color: #FFFFFF;font-size: 6rpx;margin-top: 8rpx;">•
										本次调理总时长：{{ detailInfo.conditioningDuration }}秒</view>
								</view>
								<view class="uno-w-full flex-center" style="margin-top: 12rpx;">
									<image src="../../static/images/zhidaole.png" mode="scaleToFill" class=""
										style="width: 62rpx;height: 18rpx;" @click="handleToIndex" />
								</view>
							</view>
						</view>
					</view>
				</view>

			</view>
			<!-- 穴位弹窗组件 -->
			<AcupunctureDialog v-if="isShowDialog" :detail="acupointList[groupActive]" @close="isShowDialog = false" />
		</BaseLayout>
	</view>
</template>

<style lang="scss" scoped>
	.uno-overflow-hidden {
		overflow: hidden;
	}

	.uno-c-#fff {
		color: #ffffff;
	}

	.uno-relative {
		position: relative;
	}

	.uno-absolute {
		position: absolute;
	}

	.uno-w-full {
		width: 100%;
	}

	.uno-h-100vh {
		height: 100vh;
	}

	.uno-h-full {
		height: 100%;
	}

	.uno-block {
		display: block;
	}

	.uno-m-auto {
		margin: auto;
	}

	.flex-center {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.uno-items-center {
		align-items: center;
	}

	.uno-flex {
		display: flex;
	}

	.uno-flex-wrap {
		flex-wrap: wrap;
	}

	.uno-justify-between {
		justify-content: space-between;
	}

	.uno-justify-start {
		justify-content: start;
	}

	.uno-justify-center {
		justify-content: center;
	}

	.uno-flex-col {
		flex-direction: column;
	}

	.uno-mx-auto {
		margin-left: auto;
		margin-right: auto;
	}

	.bg-dialog {
		background: url('../../static/images/tltzts.png');
		background-size: 100% 100%;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.tab-item {
		width: 14rpx;
		height: 14rpx;
		border-radius: 50%;
		background: rgba(186, 210, 255, 0.5);
		color: #2a477d;
		font-size: 11rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10rpx;
	}

	.tab-item:last-child {
		margin-right: 0;
	}

	.active {
		background: #ffffff;
		color: #1a3566;
	}

	.group-wrap {
		width: 100%;
		height: 46%;
		// overflow-y: auto;
		margin-top: 14rpx;
	}

	.bg1 {
		background: url('../../static/images/kstl_icon_dk.png');
		background-size: 100% 100%;
	}

	.bg2 {
		// background: linear-gradient(90deg, #0b2354 40%, #1a3b7e 100%);
		background: transparent;
	}

	.bg3 {
		background: url('../../static/images/btn-bg.png');
		background-size: 100% 100%;
	}
</style>